package com.iterator.config;

import com.iterator.manager.CustomSessionManager;
import com.iterator.realm.CustomRealm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;


@Configuration
public class ShiroConfig {
    @Bean
    public DefaultWebSecurityManager securityManager(CustomRealm customRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(customRealm);
        securityManager.setSessionManager(webSessionManager());
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager manager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(manager);
        //认证失败后的重定向
        factoryBean.setLoginUrl("/admin/auth/index");
        //未经授权的重定向
        factoryBean.setUnauthorizedUrl("/admin/auth/unAuth");
        Map<String, String> map = new LinkedHashMap<>();
        //不需要认证的请求
        map.put("/admin/auth/index","anon");
        map.put("/admin/auth/login","anon");
        map.put("/admin/auth/unAuth","anon");

        map.put("/wx/auth/login","anon");
        //用户注册获取验证码
        map.put("/wx/auth/regCaptcha","anon");
        map.put("/wx/auth/register","anon");
        map.put("/wx/auth/reset","anon");
        map.put("/wx/home/index","anon");
        map.put("/wx/goods/**","anon");
        map.put("/wx/brand/**","anon");
        map.put("/wx/catalog/**","anon");
        map.put("/wx/search/**","anon");
        map.put("/wx/topic/**","anon");
        map.put("/wx/comment/**","anon");
        map.put("/wx/cart/goodscount","anon");
        map.put("/wx/storage/upload","anon");
        map.put("/wx/coupon/list","anon");

        map.put("/druid/**","anon");
        map.put("/pic/**", "anon");

        //需要认证的请求
        map.put("/**","authc");

        factoryBean.setFilterChainDefinitionMap(map);
        return factoryBean;
    }

    /**
     * 声明式授权所需要注册的组件
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(
            DefaultWebSecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }

    @Bean
    public DefaultWebSessionManager webSessionManager(){
        return new CustomSessionManager();
    }
}
